package juc;

import java.util.concurrent.CountDownLatch;

/*
* CountDownLatch 闭锁：在完成某些运算时，只有其他所有的线程的运算全部完成，当前运算才继续执行
* 先阻塞，后唤醒 在CountDownLatch传入唤醒次数（线程数），当一个线程完成就将唤醒次数减一
* */
public class TestCountDownLatch {
    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(5);
        LatchDemo ld = new LatchDemo(latch);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5 ; i++) {
            new Thread(ld).start();
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}
class LatchDemo implements Runnable {

    private CountDownLatch latch;

    public LatchDemo(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        synchronized (this) {
            try {
                for (int i = 0; i < 50000; i++) {
                    if (i % 2 ==  0) {
                        System.out.println(i);
                    }
                }

            } finally {
                latch.countDown();
            }
        }


    }
}